<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>预订管理 - 酒店房间订阅系统</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css">
</head>
<body>
<div class="container">
    <header>
        <h1>预订管理</h1>
        <nav>
            <ul>
                <li><a href="${pageContext.request.contextPath}/hotel/">首页</a></li>
                <li><a href="${pageContext.request.contextPath}/hotel/available-rooms">可用房间</a></li>
            </ul>
        </nav>
    </header>

    <main>
        <div class="table-container">
            <table class="table">
                <thead>
                <tr>
                    <th>预订ID</th>
                    <th>房间ID</th>
                    <th>客户姓名</th>
                    <th>联系电话</th>
                    <th>入住日期</th>
                    <th>退房日期</th>
                    <th>总金额</th>
                    <th>状态</th>
                    <th>预订日期</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <c:forEach var="booking" items="${bookings}">
                    <tr>
                        <td>${booking.bookingId}</td>
                        <td>${booking.roomId}</td>
                        <td>${booking.customerName}</td>
                        <td>${booking.customerPhone}</td>
                        <td><fmt:formatDate value="${booking.checkInDate}" pattern="yyyy-MM-dd"/></td>
                        <td><fmt:formatDate value="${booking.checkOutDate}" pattern="yyyy-MM-dd"/></td>
                        <td>¥<fmt:formatNumber value="${booking.totalAmount}" pattern="#,##0.00"/></td>
                        <td>
                                    <span class="room-status status-${booking.status}">
                                        <c:choose>
                                            <c:when test="${booking.status == 'pending'}">待确认</c:when>
                                            <c:when test="${booking.status == 'confirmed'}">已确认</c:when>
                                            <c:when test="${booking.status == 'cancelled'}">已取消</c:when>
                                            <c:otherwise>${booking.status}</c:otherwise>
                                        </c:choose>
                                    </span>
                        </td>
                        <td><fmt:formatDate value="${booking.bookingDate}" pattern="yyyy-MM-dd"/></td>
                        <td>
                            <c:if test="${booking.status == 'pending'}">
                                <button onclick="confirmBooking(${booking.bookingId})"
                                        class="btn btn-success" style="margin-right: 0.5rem;">确认</button>
                                <button onclick="cancelBooking(${booking.bookingId}, ${booking.roomId})"
                                        class="btn btn-danger">取消</button>
                            </c:if>
                            <c:if test="${booking.status == 'confirmed'}">
                                <button onclick="cancelBooking(${booking.bookingId}, ${booking.roomId})"
                                        class="btn btn-danger">取消</button>
                            </c:if>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>

        <c:if test="${empty bookings}">
            <div class="alert alert-error">
                <p>暂无预订记录。</p>
            </div>
        </c:if>
    </main>

    <footer>
        <p>&copy; 2025 酒店房间订阅系统. 保留所有权利.</p>
    </footer>
</div>

<script>
    // 获取上下文路径
    function getContextPath() {
        const path = window.location.pathname;
        const contextPath = path.substring(0, path.indexOf('/', 1));
        return contextPath || '';
    }

    function confirmBooking(bookingId) {
        if (confirm('确认此预订吗？')) {
            const contextPath = getContextPath();
            const requestUrl = contextPath + '/hotel/confirm';

            // 构建请求参数
            const params = new URLSearchParams();
            params.append('bookingId', bookingId.toString());

            console.log('确认预订 - URL:', requestUrl, '参数:', params.toString());

            fetch(requestUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: params
            })
                .then(response => {
                    console.log('响应状态:', response.status);
                    if (!response.ok) {
                        throw new Error('网络请求失败: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('响应数据:', data);
                    alert(data.message);
                    if (data.success) {
                        location.reload();
                    }
                })
                .catch(error => {
                    console.error('请求错误:', error);
                    alert('操作失败，请重试！错误：' + error.message);
                });
        }
    }

    function cancelBooking(bookingId, roomId) {
        if (confirm('确认取消此预订吗？')) {
            const contextPath = getContextPath();
            const requestUrl = contextPath + '/hotel/cancel';

            // 构建请求参数
            const params = new URLSearchParams();
            params.append('bookingId', bookingId.toString());
            params.append('roomId', roomId.toString());

            console.log('取消预订 - URL:', requestUrl, '参数:', params.toString());

            fetch(requestUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: params
            })
                .then(response => {
                    console.log('响应状态:', response.status);
                    if (!response.ok) {
                        throw new Error('网络请求失败: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('响应数据:', data);
                    alert(data.message);
                    if (data.success) {
                        location.reload();
                    }
                })
                .catch(error => {
                    console.error('请求错误:', error);
                    alert('操作失败，请重试！错误：' + error.message);
                });
        }
    }
</script>
</body>
</html>
